package com.demo.config.websocket;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.demo.config.redis.RedisUtil;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
@ServerEndpoint("/websocket/{userId}")
public class WebSocket {

	/**
	 * 与某个客户端的连接会话，需要通过它来给客户端发送数据
	 */
	private Session session;

	/**
	 * 用户ID
	 */
	private String userId;

	/**
	 * WebSocket是当前类名
	 */
	private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();

	/**
	 * 用来存在线连接用户信息
	 */
	private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<String, Session>();

	private static String WEB_SOCKET_KEY = "web_socket_key_";

	/**
	 * 链接成功调用的方法
	 */
	@OnOpen
	public void onOpen(Session session, @PathParam(value = "userId") String userId) {
		try {
			this.session = session;
			this.userId = userId;
			webSockets.add(this);
			sessionPool.put(userId, session);
			cacheMessageContains(userId);
			log.info("【websocket消息】有新的连接，总数为:" + webSockets.size());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 链接关闭调用的方法
	 */
	@OnClose
	public void onClose() {
		try {
			webSockets.remove(this);
			sessionPool.remove(this.userId);
			log.info("【websocket消息】连接断开，总数为:" + webSockets.size());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 收到客户端消息后调用的方法
	 * @param message
	 */
	@OnMessage
	public void onMessage(String message) {
		log.info("【websocket消息】收到客户端消息:" + message);
	}

	/**
	 * 发送错误时的处理
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {

		log.error("用户错误,原因:" + error.getMessage());
		error.printStackTrace();
	}

	// 此为广播消息
	public static void sendAllMessage(String message) {
		log.info("【websocket消息】广播消息:" + message);
		for (WebSocket webSocket : webSockets) {
			try {
				if (webSocket.session.isOpen()) {
					webSocket.session.getAsyncRemote().sendText(message);
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 此为单点消息
	@Async
	public void sendOneMessage(String userId, String message) {

		if (sessionPool.size() <= 0 || ObjectUtils.isEmpty(sessionPool.get(userId))) {
			cacheMessagePut(userId, message);
			return;
		}
		try {
			Session session = sessionPool.get(userId);
			if (session != null && session.isOpen()) {
				log.info("【websocket消息】 单点消息:" + message);
				// 异步 会报错-待处理
				// session.getAsyncRemote().sendText(message);
				// 同步
				session.getBasicRemote().sendText(message);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 此为单点消息(多人)
	public void sendMoreMessage(String[] userIds, String message) {
		for (String userId : userIds) {
			Session session = sessionPool.get(userId);
			if (session != null && session.isOpen()) {
				try {
					log.info("【websocket消息】 单点消息:" + message);
					session.getAsyncRemote().sendText(message);
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 查询是否有离线消息并推送
	 */
	public void cacheMessageContains(String userId) {

		String key = WEB_SOCKET_KEY + userId;
		List<String> range = new ArrayList();
		// 是否有暂存的消息，如果有则发送消息
		if (RedisUtil.redis.hasKey(key)) {
			range = RedisUtil.redis.opsForList().range(key, 0, -1);
		}

		if (CollectionUtils.isNotEmpty(range) && range.size() > 0) {
			range.forEach(msg -> {
				sendOneMessage(userId, msg);
			});
			RedisUtil.redis.delete(key);
		}

	}

	/**
	 * 暂存离线消息
	 */
	public void cacheMessagePut(String userId, String message) {
		String key = WEB_SOCKET_KEY + userId;
		if (StringUtils.isNotEmpty(message)) {
			RedisUtil.redis.opsForList().rightPush(key, message);
			log.info(WEB_SOCKET_KEY + userId + "消息暂存成功");
		}
	}

}
